﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Kooboo.HtmlFunc.Function;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.HtmlFunc.Analysis.Visitors
{
    public class StyleTagVisitor : VisitorBase
    {
        public StyleTagVisitor(VisitorContext context)
            : base(context)
        {
        }

        public override void VisitNode(HtmlNode node)
        {
            if (node.Is("STYLE"))
            {
                var styleTag = Provider.Factory.GetProvider<IStyleTag>();
                styleTag.Node = node;
                styleTag.IsLink = false;
                this.Context.Result.StyleTags.Add(styleTag);
            }
            else if (node.Is("LINK") && (StringEqual(node.Attr("rel"), "Stylesheet") || StringEqual(node.Attr("type"), "text/css")))
            {
                var styleLinkTag = Provider.Factory.GetProvider<IStyleTag>();
                styleLinkTag.Node = node;
                styleLinkTag.IsLink = true;
                this.Context.Result.StyleTags.Add(styleLinkTag);
            }
        }

        private static bool StringEqual(string str1, string str2)
        {
            str1 = (str1 ?? string.Empty).Trim();
            str2 = (str2 ?? string.Empty).Trim();
            return str1.IgnoreCaseEquals(str2);
        }
    }
}
